//
//  YH_SystemSettingViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/10/25.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_SystemSettingViewController.h"
#import "FunChoiceViewController.h"//功能选择
#import "ModelChoiceViewController.h"//模板选择


@interface YH_SystemSettingViewController ()<UITableViewDataSource,UITableViewDelegate,ASIHTTPRequestDelegate>{
    
    UITableView *_tableView;
    NSArray *items;
    NSArray *pictures;
    
    //绑定view
    
    __weak IBOutlet UIView *backgroundView;
    
    __weak IBOutlet UITextField *bandingText;
    
    __weak IBOutlet UIButton *canBtn;
    
    __weak IBOutlet UIButton *postBtn;
    __weak IBOutlet UIView *subBackgroundView;
    //绑定请求
    ASIFormDataRequest *_request;
    //参数
    NSString *action;
    NSDictionary *paramsDict;
    
    MBProgressHUD *postHud;
}

@end

@implementation YH_SystemSettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    backgroundView.layer.cornerRadius = 5.0;
    subBackgroundView.layer.cornerRadius = 5.0;
    backgroundView.hidden = YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //标题
    self.navigationItem.title = @"系统设置";
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    //设置功能选项
    items = @[@"账号绑定",@"功能选择",@"模板选择"];
    pictures = @[@"u18.png",@"u20.png",@"u22.png"];
    [self setUI];
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark IBAction Methods

- (IBAction)postBanding:(id)sender {
    if (bandingText.text.length == 0) {
        return;
    }
    [self postInformationWithNum:bandingText.text];
    backgroundView.hidden = YES;
}

- (IBAction)cancelBtn:(id)sender {
    backgroundView.hidden = YES;
}
#pragma mark Custom Methods

-(void)setUI{
    UIScreen *screen = [UIScreen mainScreen];
    //
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(30, 40, screen.bounds.size.width - 30 * 2, items.count * 49)];
    //无分割线
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.layer.cornerRadius=5.0;
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
}


-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark TableView Delegate Method

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"OtherFuntionViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"OtherFuntionViewCell" owner:nil options:nil][0];
    }
    NSUInteger row = [indexPath row];
    UILabel *lbl = (UILabel *)[cell.contentView viewWithTag:2];
    
    lbl.text = items[row];
    //添加图片
    UIImageView *img_view = (UIImageView *)[cell.contentView viewWithTag:1];
    img_view.image = [UIImage imageNamed:pictures[row]];

    return cell;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return items.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.row) {
        case 0:{
            backgroundView.hidden = NO;
            bandingText.keyboardType = UIKeyboardTypeNumberPad;
            [self.view bringSubviewToFront:backgroundView];
                }break;
        case 1:{
            FunChoiceViewController *FCVC = [[FunChoiceViewController alloc]initWithNibName:@"FunChoiceViewController" bundle:nil];
            
            [self.navigationController pushViewController:FCVC animated:YES];
        }break;
        case 2:{
            ModelChoiceViewController *MCVC = [[ModelChoiceViewController alloc]initWithNibName:@"ModelChoiceViewController" bundle:nil];
            
            [self.navigationController pushViewController:MCVC animated:YES];

        }break;
        default:
            break;
    }
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark UIAlertView Delegate


/* 提交发布信息请求 */
- (void)postInformationWithNum:(NSString*)NumStr{
    
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        
            action = @"cmobileaddandupdata";
            if (!postHud || postHud.hidden == YES) {
                // 提示正在加载数据...
                postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                postHud.labelText = @"正在发布，请稍后...";
            }
            
            _request = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
            _request.requestMethod = @"POST";
            // 设置超时时间
            _request.timeOutSeconds = 60;
            _request.delegate = self;
            // 设置参数
            NSLog(@"%@ || %@",UID,UNAME);
            paramsDict = @{@"cid":UID,@"uid":UNAME,@"cmobile":NumStr};//
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
            
            NSData *paramsData = [result toGBKEncodingData];
            _request.postBody = [paramsData mutableCopy];
            
            [_request startAsynchronous];
        }
}
#pragma mark Http Methods
- (void)requestFinished:(ASIHTTPRequest *)request {
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    NSLog(@"%@",result);
    // 1. 是否解析有错误
    if (!err) {
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            [postHud hide:YES];
            // 提示发布成功
            [UIView animateWithDuration:0 animations:^{
            [SVProgressHUD showSuccessWithStatus:@"绑定成功！"];
                    //[self.navigationController popViewControllerAnimated:YES];
                
            } completion:^(BOOL finished) {
                
            }];
        } else {
            [postHud hide:YES];
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
    } else {
        [postHud hide:YES];
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request {
    
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

-(void)dealloc{
    [_request cancel];
    postHud = nil;
}

@end
